import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/role_personnel_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/apply_user_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/identification_config_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/job_plan_details_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/work_tool_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_plan_request/job_plan_request_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_plan_request/planning_request/planning_request_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/special_list_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class PlanRiskIdentificationController extends GetxController {
  final controller = Get.find<PlanningRequestController>();

  /// 外部列表controller
  final specialListController = Get.find<SpecialListController>();

  /// 作业计划controller
  final jobPlanRequestController = Get.find<JobPlanRequestController>();

  /// 计划申请详情实体
  JobPlanDetailsEntity jobPlanDetailsEntity = JobPlanDetailsEntity();

  // 风险辨识选择列表
  List<IdentificationConfigEntity> riskIdentificationList = [];

  // 工具集选择列表
  List<WorkToolEntity> toolList = [];

  // 选中的风险辨识结果
  List<IdentificationConfigEntity> riskIdentificationResult = [];

  // 选中的工具集
  List<WorkToolEntity> toolSet = [];

  // 是否为确认
  RxBool isConfirm = false.obs;

  // 动火作业申请人
  List<RolePersonnelEntity> applicant = [];

  // 字典查出的作业类型
  List<GetDictAllEntity> workType = DictDataInfo.specialJobType;

  // 作业列表
  // List<String> jobList = [];

  // 推荐作业类型
  String recommendType = '';

  // 选中的作业
  List<GetDictAllEntity> selectedJobList = [];

  // 选中的作业申请人和监护人
  List<ApplyUserEntity> selectedJobApplicant = [];

  // 历史中已经选中的作业和负责人信息
  List<ApplyUserEntity> originalJobList = [];

  // 涉及作业点击
  void designJobClick(GetDictAllEntity bean) {
    // 判断是否已经选中
    if (selectedJobList.any((object) => object.id == bean.id)) {
      // 删除选中的作业
      selectedJobList.removeWhere((object) => object.id == bean.id);
      // 删除选中的作业申请人和监护人
      selectedJobApplicant.removeWhere((object) => object.ticketBigTypeId == bean.id);
    } else {
      selectedJobList.add(bean);
      // 添加作业到人员选择列表中
      addSelectedJobListByType(bean);
    }
    update();
  }

  // 添加作业到人员选择列表中
  void addSelectedJobListByType(GetDictAllEntity bean) {
    // final String ticketBigTypeId = DictDataInfo.specialJobType
    //         .firstWhere((element) => element.dictionaryLabel == type)
    //         .id ??
    //     '';
    // 选中列表中不存在该作业才添加
    if (!selectedJobApplicant.any((object) => object.ticketBigTypeId == bean.id)) {
      final applyUserEntity = ApplyUserEntity()
        ..selectedJobList = bean.dictionaryLabel
        ..ticketBigTypeName = bean.dictionaryLabel
        ..ticketBigTypeId = bean.id;
      selectedJobApplicant.add(applyUserEntity);
    }
  }

  // 获取风险辨识结果列表
  void queryRiskIdentificationList() async {
    final data = {
      'typeId': '',
    };

    final res = await HttpUtil()
        .generateGetRequest<List<IdentificationConfigEntity>>(
          Interface.riskIdentificationListUrl,
          queryParameters: data,
        )
        .execute();

    res.onSuccess((result) {
      riskIdentificationList = result.data ?? [];
      // 设置之前已经选择的风险辨识结果
      _initIdentification();
      // 获取作业工具列表
      queryJobToolList(isInitTool: true);
      update();
    });
  }

  // 初始化设置风险辨识结果
  void _initIdentification() {
    for (String i in jobPlanDetailsEntity.ticketIdentityId!) {
      for (IdentificationConfigEntity j in riskIdentificationList) {
        if (j.id == i) {
          riskIdentificationResult.add(j);
        }
      }
      update();
    }
  }

  /// 获取风险辨识结果id集合
  List<String> _getIdentificationIds() {
    final List<String> identificationIds = [];
    for (var item in riskIdentificationResult) {
      identificationIds.add(item.id!);
    }
    return identificationIds;
  }

  /// 工具集选择
  void selectToolSet() async {
    if (riskIdentificationResult.isEmpty) {
      AppToast.show('请选择风险辨识结果');
      return;
    }
    await queryJobToolList();
    CustomSelectFunction.selectMultipleBottomSheet<WorkToolEntity>(
      title: '工具集选择',
      dataList: toolList,
      checkedList: toolSet,
      onCallBack: (value) {
        toolSet = value;
        update();
      },
    );
  }

  // 获取作业工具列表
  Future<void> queryJobToolList({bool isInitTool = false}) async {
    final data = {
      'keyWords': '', // 关键词
      'workTypeId': '', // 作业类型id
      'identificationIds': _getIdentificationIds()
    };

    final res = await HttpUtil()
        .generateGetRequest<List<WorkToolEntity>>(
          Interface.jobToolListUrl,
          queryParameters: data,
        )
        .execute();

    res.onSuccess((result) {
      toolList = result.data ?? [];
      if (isInitTool) {
        // 设置之前已经选择的工具集
        _initToolConfig();
      }
      update();
    });
  }

  // 初始化设置工具集
  void _initToolConfig() {
    for (String i in jobPlanDetailsEntity.ticketToolId!) {
      for (WorkToolEntity j in toolList) {
        if (j.id == i) {
          toolSet.add(j);
        }
      }
      update();
    }
  }

  // 根据辨识结果及工器具查询作业列表
  void queryJobList() async {
    final List<String> ticketIdentityIds = [];
    final List<String> ticketToolIds = [];
    if (riskIdentificationResult.isEmpty) {
      AppToast.show('请选择风险辨识结果');
      return;
    }
    if (toolSet.isEmpty) {
      AppToast.show('请选择工器具');
      return;
    }
    for (var element in riskIdentificationResult) {
      ticketIdentityIds.add(element.id ?? '');
    }
    for (var element in toolSet) {
      ticketToolIds.add(element.id ?? '');
    }
    final data = {
      'ticketIdentityIds': ticketIdentityIds, // 风险辨识结果ID[数组] String
      'ticketToolIds': ticketToolIds, // 风险辨识工器具ID[数组] String
    };

    /// 请求推荐作业列表数据
    final res = await HttpUtil()
        .generatePostRequest<List<ApplyUserEntity>>(
          Interface.jobListUrl,
          data: data,
        )
        .execute();

    res.onSuccess((result) {
      if (result.data != null) {
        // 清空之前的数据
        selectedJobList.clear();
        selectedJobApplicant.clear();
        // 添加历史数据
        _setOriginalCharge();
        for (var item in result.data!) {
          // 从字典中查找id相同的作业对象
          final other = workType.firstWhere((other) => item.ticketTypeId == other.id, orElse: GetDictAllEntity.new);
          // 如果不存在就添加选择的作业
          if (!selectedJobList.any((object) => object.id == other.id)) {
            selectedJobList.add(other);
          }
          // 添加作业到人员选择列表中
          addSelectedJobListByType(other);
        }
        recommendType = selectedJobList.map((e) => e.dictionaryLabel).join('、');
        isConfirm.value = true;
        update();
      } else {
        AppToast.show('未查询到相关作业！');
      }
    });
  }

  // 获取作业计划下小票作业列表及负责人
  void getCharge() async {
    final data = {
      'ticketPlanId': jobPlanDetailsEntity.id, // 作业计划id
    };

    final res = await HttpUtil()
        .generateGetRequest<List<ApplyUserEntity>>(
          Interface.getCharge,
          queryParameters: data,
        )
        .execute();

    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        originalJobList = result.data!;
        // 设置之前的数据不可修改
        for (var item in originalJobList) {
          item.allowModification = false;
        }
        _setOriginalCharge();
        isConfirm.value = true;
      }
    });
  }

  // 将之前已经选中的数据添加到页面显示中
  void _setOriginalCharge() {
    for (var item in originalJobList) {
      // 查找id相同的作业对象
      final other = workType.firstWhere((other) => item.ticketBigTypeId == other.id, orElse: GetDictAllEntity.new);
      // 添加到作业选择列表中
      selectedJobList.add(other);
      item.selectedJobList = other.dictionaryLabel;
      // 添加到人员选择列表中
      selectedJobApplicant.add(item);
    }
    recommendType = originalJobList.map((e) => e.selectedJobList).join('、');
  }

  // 作业辨识上传
  void jobIdentification() async {
    final List<String> ticketIdentityIds = [];
    final List<String> ticketToolIds = [];
    if (riskIdentificationResult.isEmpty) {
      AppToast.show('请选择风险辨识结果');
      return;
    }
    if (toolSet.isEmpty) {
      AppToast.show('请选择工器具');
      return;
    }
    if (selectedJobList.isEmpty) {
      AppToast.show('请选择涉及作业');
      return;
    }
    // 判断作业申请人不能有没选的
    for (var i in selectedJobApplicant) {
      if (i.applyUserId == null && i.applyUserName == null) {
        AppToast.showWarning('请选择${i.selectedJobList}申请人');
        return;
      }
      if (i.guardianList.isEmpty) {
        AppToast.showWarning('请选择${i.selectedJobList}监护人');
        return;
      }
      // if (i.guardianUserId == null && i.guardianUserName == null) {
      //   AppToast.showWarning('请选择${i.selectedJobList}监护人');
      //   return;
      // }
    }

    for (var element in riskIdentificationResult) {
      ticketIdentityIds.add(element.id ?? '');
    }
    for (var element in toolSet) {
      ticketToolIds.add(element.id ?? '');
    }
    final data = {
      'id': jobPlanDetailsEntity.id, //作业计划ID
      'ticketIdentityId': ticketIdentityIds, // 风险辨识结果ID String
      'ticketToolId': ticketToolIds, // 风险辨识工器具ID String
      'workTypes': selectedJobApplicant
    };
    // 加载框
    // SmartDialog.showLoading(backDismiss: false);
    final res = await HttpUtil()
        .generatePostRequest(
          Interface.jobIdentificationUrl,
          data: data,
        )
        .execute(isShowLoading: true);

    res.onSuccess((result) {
      if (result.data != null) {
        Get.back();
        // SmartDialog.dismiss();
        specialListController.refreshPage();
        AppToast.showSuccess('辨识成功');
      }
    });

    res.onError((result) {
      // SmartDialog.dismiss();
      AppToast.showError('辨识失败');
    });
  }

  /// 获取作业申请人
  /// [roleName] 角色名称
  /// [type] 角色类型
  void queryApplicant({required String roleName, required String type, required ApplyUserEntity bean}) async {
    if (!bean.allowModification) {
      AppToast.showError('已开作业票,不可编辑');
      return;
    }
    Get.toNamed(AppRoutes.personnelSelection, arguments: {
      'queryParameters': {'roleName': roleName},
      'isRadio': roleName == '作业申请人',
    })?.then((value) {
      if (roleName == '作业申请人') {
        //如果不为空则设置人员信息
        if (value != null && value is List<RolePersonnelEntity>) {
          // 添加申请人数据
          final int index = selectedJobApplicant.indexWhere((element) => type.startsWith(element.selectedJobList.toString()));
          if (index != -1) {
            selectedJobApplicant[index].applyUserId = value.first.getId();
            selectedJobApplicant[index].applyUserName = value.first.getShowName();
          } else {
            AppToast.showError('数据异常');
          }
        }
      }
      if (roleName == '监护人') {
        //如果不为空则设置人员信息
        if (value != null && value is List<RolePersonnelEntity>) {
          // 添加申请人数据
          final int index = selectedJobApplicant.indexWhere((element) => type.startsWith(element.selectedJobList.toString()));
          if (index != -1) {
            // 清空数据
            selectedJobApplicant[index].guardianList.clear();
            // 循环添加数据
            for (var item in value) {
              selectedJobApplicant[index].guardianList.add(ExecuteTicketReceiptListOperatorLists()
                ..operatorUserId = item.getId()
                ..operatorUserName = item.getShowName());
            }
          } else {
            AppToast.showError('数据异常');
          }
        }
      }
      // 判断 [selectedJobApplicant] 是否包含 [value.first]
      // if (roleName.endsWith('申请人')) {
      //   final int index = selectedJobApplicant.indexWhere(
      //       (element) => type.startsWith(element.selectedJobList.toString()));
      //   if (index != -1) {
      //     selectedJobApplicant[index].applyUserId = value.first.userId;
      //     selectedJobApplicant[index].applyUserName = value.first.userName;
      //   } else {
      //     AppToast.showError('数据异常');
      //   }
      // } else {
      //   final int index = selectedJobApplicant.indexWhere(
      //       (element) => type.startsWith(element.selectedJobList.toString()));
      //   if (index != -1) {
      //     selectedJobApplicant[index].guardianUserId = value.first.userId;
      //     selectedJobApplicant[index].guardianUserName = value.first.userName;
      //   } else {
      //     AppToast.showError('数据异常');
      //   }
      // }
      update();
    });
  }

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null && Get.arguments is String) {
      jobPlanDetailsEntity = jobPlanRequestController.jobPlanDetailsEntity;
      // 获取风险辨识结果列表
      queryRiskIdentificationList();
      // 获取作业计划下小票作业列表及负责人
      getCharge();
    }
  }

  // 下一步或者确定方法
  void nextOrConfirm() {
    if (isConfirm.value) {
      jobIdentification();
    } else {
      queryJobList();
    }
  }
}
